import itertools
import datetime
import hashlib

# 生成密码
def generateLibrary(library, length):
    library = itertools.product(library, repeat=length)
    print("枚举完成")
    dic = open("passwotdlib{}.txt".format(length), "w", encoding='utf-8')
    for i in library:
        dic.writelines(i)
        dic.writelines("\n")
    dic.close()

# 进行字典攻击
def dictAttack(path, password):
    file = open(path)
    for passwords in file:
        passwords = passwords.split("\n")[0]
        if password == hashlib.md5(passwords.encode(encoding="utf-8")).hexdigest():
            print("破解成功，你的密码是：{}".format(passwords))
            break
    file.close()
    return

if __name__ == "__main__":
    lowercase = "abcdefghijklmnopqrstuvwxyz"
    uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    number = "0123456789"
    root = lowercase + uppercase + number
    opassword = "uestc"     # 原始密码
    rpassword = hashlib.md5(opassword.encode(encoding="utf-8")).hexdigest()     #经过 md5 加密的密码

    # 生成 1 到 6 位密码的字典
    for i in range(1, 6):
        start = datetime.datetime.now()
        generateLibrary(root, length=i)
        end = datetime.datetime.now()
        print("成功生成{}位密码字典!\n".format(i))
        print("用时：")
        print(end - start)
        print("\n")

    # 进行字典攻击
    start = datetime.datetime.now()
    dictAttack("passwotdlib5.txt", rpassword)
    end = datetime.datetime.now()
    print("用时：")
    print(end - start)
    print("\n")